package com.itheima.reggie.controller;

import com.itheima.reggie.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    //文件上传
    @PostMapping("/{upload}")
    public Result upload(MultipartFile file) throws IOException {
        //获取原始文件名
        String filename = file.getOriginalFilename();
        //对原始文件名进行截取,获取原始文件名的后缀
        int index = filename.lastIndexOf(".");
        String newFilename = filename.substring(index);

        //利用UUID从新生成一个文件名,以免发生重名被覆盖问题
        String name = UUID.randomUUID() + newFilename;

        //创建一个目录对象
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }

        //将临时文件存储到指定的位置
        file.transferTo(new File(basePath + name));

        return Result.success(name);
    }

    //文件下载
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response) throws IOException {

        //获取文件的访问路径
        String fileName = basePath + name;

        byte[] bytes = FileCopyUtils.copyToByteArray(new File(fileName));

        //将图片以字节数组的形式返回给浏览器
        response.getOutputStream().write(bytes);

    }


}
